package com.example.griddemo.adapter;

import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.viewmodel.Goods;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.ViewHolder> {
    private List<Goods> goodsList;

    public GoodsListAdapter(List<Goods> goodsList) {
        this.goodsList = goodsList != null ? goodsList : new ArrayList<>();
    }

    public void updateData(List<Goods> newList) {
        this.goodsList = newList != null ? newList : new ArrayList<>();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_goods, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Goods goods = goodsList.get(position);
        holder.bind(goods);
    }

    @Override
    public int getItemCount() {
        return goodsList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivImage;
        TextView tvName;
        TextView tvBrief;
        TextView tvPrice;
        TextView tvOriginalPrice;

        ViewHolder(View itemView) {
            super(itemView);
            ivImage = itemView.findViewById(R.id.iv_goods_image);
            tvName = itemView.findViewById(R.id.tv_goods_name);
            tvBrief = itemView.findViewById(R.id.tv_goods_brief);
            tvPrice = itemView.findViewById(R.id.tv_goods_price);
            tvOriginalPrice = itemView.findViewById(R.id.tv_goods_original_price);
        }

        void bind(Goods goods) {
            Glide.with(itemView)
                    .load(goods.getPicUrl())
                    .into(ivImage);

            tvName.setText(goods.getName());
            tvBrief.setText(goods.getBrief());
            tvPrice.setText(String.format("¥%.2f", goods.getRetailPrice()));

            if (goods.getCounterPrice() != null) {
                tvOriginalPrice.setText(String.format("¥%.2f", goods.getCounterPrice()));
                tvOriginalPrice.setPaintFlags(
                        tvOriginalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                tvOriginalPrice.setVisibility(View.VISIBLE);
            } else {
                tvOriginalPrice.setVisibility(View.GONE);
            }
        }
    }
}